package com.example.douyin.service.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.example.douyin.service.WatermarkService;
import com.example.douyin.util.CommonUtil;
import com.example.douyin.util.PathUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WatermarkServiceImpl implements WatermarkService {

    private Logger logger = Logger.getLogger(WatermarkServiceImpl.class);

    @Value("${douyinUrL}")
    private String commonUrl;

    /**
     * 常量
     */
    private static String MSG = "对应的短视频集合为空";

    /**
     * 对应的原生的目录
     */
    private static String ORIGINDIR = "SanMu";

    /**
     * 短链接的下载对应的抖音的字节流的方式并且返回对应的相应！
     *
     * @param shortUrls 短的抖音的链接集合
     * @param response 响应体
     */
    @Override
    public void getBgmAndMusic(List<String> shortUrls, HttpServletResponse response) throws Exception {
        //4.64 cAG:/ 科院爱我，我爱科院，爱我科院。%%大疆air2s 总感觉色彩感差一些，滤镜差一点感觉  https://v.douyin.com/Fse9w29/ 复制此链接，打开Dou音搜索，直接观看视频！

        // 抖音去水印功能  3.00 HII:/ 妹妹你大胆的往前走%%画画 %%插画 %%绘画  https://v.douyin.com/F4pArJa/ 复制此链接，打开Dou音搜索，直接观看视频！

        if(CollUtil.isEmpty(shortUrls)) {
            throw new Exception(MSG);
        }
        shortUrls.parallelStream().forEach(shortUrl -> {
            // 将文件下载到本机地址
            downloadMusicAndVideo(shortUrl);
        });
        //  将下载的文件输出到zip,然后清空本地文件！！
        String originDir = PathUtil.getCommonPath(ORIGINDIR);
        //生成zip文件
        String target = PathUtil.getCommonPath("/rb.zip");
        File rb = new File(target);
        if(!rb.getParentFile().exists()) {
            rb.getParentFile().mkdirs();
        }
        FileUtil.touch(target);
        ZipUtil.zip(originDir, target, true);
        File file = FileUtil.touch(target);
        InputStream fis = FileUtil.getInputStream(file);
        OutputStream outputStream = response.getOutputStream();
        try {
            //TODO 将压缩包流返回
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            response.reset();
            String title = "抖音去水印";
            String fileName = URLEncoder.encode(title, "UTF-8").replaceAll("\\+", "%20");
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            // 不同类型的文件对应不同的MIME类型
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition","attachment; filename="+fileName+".zip");
            OutputStream toClient = new BufferedOutputStream(outputStream);
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            fis.close();
            //删除文件夹下文件
        }catch (Exception e){
            logger.error(e.getMessage());
        }finally {
            FileUtil.del(target);
            FileUtil.del(originDir);
        }

    }

    private void downloadMusicAndVideo(String shortUrl) {

        Map header = MapUtil.newHashMap();

        header.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");

        HttpResponse executeB = HttpUtil.createGet(shortUrl).addHeaders(header).execute();

        String strUrl = executeB.body();

        List match = CommonUtil.match(strUrl);

        strUrl = match.get(0).toString();

        String ids = strUrl.substring(strUrl.indexOf("video/"), strUrl.lastIndexOf("/")).replace("video/", "");

        String videoUrl = commonUrl + ids;

        String body = HttpUtil.createGet(videoUrl).execute().body();

        JSONObject entries = new JSONObject(body);

        String videoAddress = entries.getJSONArray("item_list").getJSONObject(0).getJSONObject("video").getJSONObject("play_addr").getJSONArray("url_list").get(0).toString();

        String musicAddress = entries.getJSONArray("item_list").getJSONObject(0).getJSONObject("music").getJSONObject("play_url").get("uri").toString();

        HashMap headers = MapUtil.newHashMap();

        headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");

        String replace = videoAddress.replace("playwm", "play");

        logger.info(replace);

        logger.info(musicAddress);

        HttpResponse execute = HttpUtil.createGet(replace).addHeaders(headers).execute();

        HttpResponse music = HttpUtil.createGet(musicAddress).addHeaders(headers).execute();

        String finalVideoAddress = execute.header("Location");

        CommonUtil.downloadVideo(finalVideoAddress, ids);

        CommonUtil.downloadMusic(music.bodyStream(), ids);
    }
}
